var _uri = 'item_sales_ranking_inquiry';
var _uri_query = 'item_sales_ranking';
$(function() {
	initDP();
});
function initDP(){
	var date_type = getRadioVal('time');
	var range = getDateRange(new Date(),date_type,'-');
	$(".dpicker").datepicker({onSelect:doOnSelect,changeMonth: true,changeYear: true,maxDate:0,minDate:-10*365,onChangeMonthYear:changeMonthYear,beforeShow:doBeforeShow,dateFormat: 'yy/mm/dd', showOn: 'both',  buttonImageOnly: true, buttonImage: 'images/calendar.png'}).val(range);
	$('input[name=time]').eq(0)[0].checked=true;
	$('input[name=time]').change(function(){
		var date_type = getRadioVal('time');
		var range = getDateRange(new Date(), date_type, '-');
		$(".dpicker").focus(function(){
			var type = getRadioVal('time');
			if(type=='year')
				$("#ui-datepicker-div table, select.ui-datepicker-month").hide();
			else if(type=='month')
				$("#ui-datepicker-div table").hide();
		}).val(range);
	});
	function doBeforeShow(input, inst){
		var type = getRadioVal('time');
		var val = $('#'+inst.id).val();
		$(this).datepicker('option', 'stepMonths', type=='year'?12:1);
		$(this).datepicker('option', 'showButtonPanel', type=='month'||type=='year');
		var height = $(input).height();
		var offset = $(input).offset();
		window.setTimeout(function(){
	        inst.dpDiv.css({top:(offset.top+height+4)+'px',left: offset.left+'px'});
	        $('#'+inst.id).val(val);
	    },1);
	}
	function changeMonthYear(year, month, inst){
		var type = getRadioVal('time');
		if(type=='month' || type=='year'){
			var range = getDateRange(new Date(year,month-1,1), type, '-');
			$('#'+inst.id).val(range);
		}
	}
	function doOnSelect(dateText, inst){
		var date_type = getRadioVal('time');
		var date = $(this).datepicker('getDate');
		var range = getDateRange(date, date_type, '-');
		$('#'+inst.id).val(range);
	}
}

function query(){
	var datas = {fun:'query',date_type:getRadioVal('time')};
	var oDate = $('#date_range');
	oDate.val($.trim(oDate.val()));
	var tok = oDate.val().split(' ~ ');
	if(oDate.val()==''){
		alert('请输入期间');oDate.focus();return;
	}else if((tok.length!=2 || !isDateStr(tok[0]) || !isDateStr(tok[1]))){
		alert('日期有误');oDate.focus();return;
	}else if(compareDateStr(tok[0], tok[1])<0){
		alert('结束日期应大于开始日期');oDate.focus();return;
	}
	datas['date_range'] = oDate.val();
	var _date_type = datas['date_type'];
	var begin_time = tok[0].replace(/\-/g,'/');
	var date = new Date(begin_time);
	var prevDate = new Date(begin_time);
	if(_date_type=='week')
		prevDate.setDate(prevDate.getDate()-7);
	else if(_date_type=='month')
		prevDate.setMonth(prevDate.getMonth()-1);
	else if(_date_type=='year')
		prevDate.setDate(prevDate.getDate()-365);
	var range = getDateRange(date, _date_type, '-');
	var prevRange = getDateRange(prevDate, _date_type, '-');
	datas['prev_date_range'] = prevRange;
	postHandler(_uri,datas, function(val){
		window.location=_uri_query+'.html';
		return false;
	});
}